package com.lin.sys.service.impls;


import com.lin.sys.entity.SysRoleMenu;
import org.apache.dubbo.config.annotation.Service;
import com.lin.common.service.impl.BaseService;
import com.lin.sys.dao.SysRoleMapper;
import com.lin.sys.dao.SysRoleMenuMapper;
import com.lin.sys.entity.SysRole;
import dto.SysRoleDto;
import org.springframework.beans.factory.annotation.Autowired;
import service.RoleMenuService;
import service.RoleService;
import service.UserRoleService;
import tk.mybatis.mapper.entity.Example;
import util.BeanUtils;
import util.ResponseVo;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
public class RoleServiceImpl extends BaseService<SysRole> implements RoleService {
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;
    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private UserRoleService userRoleService;
    @Override
    public List<SysRoleDto> findUserRole(Long userid) {
        List<SysRole> userRole = sysRoleMapper.findUserRole(userid);
        return BeanUtils.copyList(userRole,SysRoleDto.class);
    }

    @Override
    public ResponseVo addRole(SysRoleDto role, Long[] menuIds) {
        SysRole sysRole=new SysRole();
        BeanUtils.copyProperties(role,sysRole);
        role.setCreateTime(new Date());
        this.save(sysRole);
        this.setRoleMenu(sysRole, menuIds);
        return ResponseVo.ok("新增成功");
    }

    @Override
    public ResponseVo updateRole(SysRoleDto role, Long[] menuIds) {
        SysRole sysRole=new SysRole();
        BeanUtils.copyProperties(role,sysRole);
        role.setModifyTime(new Date());
        this.updateNotNull(sysRole);
        Example example = new Example(SysRoleMenu.class);
        example.createCriteria().andCondition("role_id=", role.getRoleId());
        this.sysRoleMenuMapper.deleteByExample(example);
        setRoleMenu(sysRole, menuIds);
        return ResponseVo.ok("修改成功");
    }

    @Override
    public List<Long> findMenuByRole(Long id) {
        return sysRoleMenuMapper.findMenuByRole(id);
    }

    @Override
    public ResponseVo deleteRole(Long roleId) {
        this.delete(roleId);
        roleMenuService.deleteByRoleId(roleId);
        userRoleService.deleteByRoleId(roleId);
        return ResponseVo.ok("删除成功");
    }

    @Override
    public List<SysRoleDto> selectTotal() {
        List<SysRole> sysRoles = this.selectAll();
        return BeanUtils.copyList(sysRoles, SysRoleDto.class);
    }

    private void setRoleMenu(SysRole role,Long[] menuIds){
        Arrays.stream(menuIds).forEach(id -> {
            SysRoleMenu rm = new SysRoleMenu();
            rm.setMenuId(id);
            rm.setRoleId(role.getRoleId());
            sysRoleMenuMapper.insert(rm);
        });
    }
}
